package com.sline.Socket;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class Demo3_SendReceive {
    public static void main(String[] args) {
        new Receiver().start();
        new Sender().start();
    }
}

class Receiver extends Thread {
    @Override
    public void run() {
        try {
            // 创建socket, 相当于创建码头
            DatagramSocket socket = new DatagramSocket(6666);
            // 创建packet, 相当于创建集装箱
            DatagramPacket packet = new DatagramPacket(new byte[1024], 1024);

            while (true) {
                // 接收数据
                socket.receive(packet);

                //获取数据
                byte[] arr = packet.getData();
                // 获取有效的字节个数
                int len = packet.getLength();

                String receivedMsg = new String(arr, 0, len);
                String ip = packet.getAddress().getHostAddress();
                int port = packet.getPort();
                System.out.println(ip + ":" + port + " " + receivedMsg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class Sender extends Thread {
    @Override
    public void run() {
        try {
            // 创建键盘录入对象
            Scanner sc = new Scanner(System.in);
            // 创建socket
            DatagramSocket socket = new DatagramSocket();

            while (true) {
                String line = sc.nextLine();

                if ("quit".equals(line)) {
                    break;
                } else {
                    // 创建packet
                    DatagramPacket packet = new DatagramPacket(line.getBytes(), line.getBytes().length, InetAddress.getByName("127.0.0.1"), 6666);
                    // 将数据发出去
                    socket.send(packet);
                }
            }

            // 关闭码头
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}